{include file="common/header"/}
<style>
    .layui-iconpicker-body.layui-iconpicker-body-page .hide {
        display: none;
    }
</style>
<div class="lemo-container">
    <div class="lemo-main">
        <div class="admin-main layui-anim layui-anim-upbit">
            <fieldset class="layui-elem-field layui-field-title">
                <legend>{:lang('add')}商品</legend>
            </fieldset>
            <form class="layui-form layui-form-pane" lay-filter="form">

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">选择店铺</label>
                        <div class="layui-input-inline">
                            <select name="shop_id" id="shop" lay-verify="required" lay-search="">
                                <option value="">直接选择或搜索选择</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品名称</label>
                    <div class="layui-input-block">
                        <input type="text" lay-verify="required" name="goods_name" required placeholder="请输入商品名称"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="test1">上传封面图片</button>
                    <div class="layui-upload-list">
                        <img style="max-width: 300px;max-height: 250px;" class="layui-upload-img" id="demo1">
                        <p id="demoText"></p>
                    </div>
                </div>

                <div class="layui-upload">
                    <button type="button" class="layui-btn" id="test2">上传商品轮播图</button>
                    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;width: 88%">
                        预览图：
                        <div class="layui-upload-list uploader-list" style="overflow: auto;" id="uploader-list">
                        </div>
                    </blockquote>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-inline">
                        <select name="category" id="category" lay-filter="category" lay-verify="require"></select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="category_two" id="category_two" lay-filter="category_two" lay-verify="require"></select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">产地</label>
                    <div class="layui-input-block">
                        <input type="text" name="address" lay-verify="required" placeholder="请输入产地"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品重量</label>
                    <div class="layui-input-block">
                        <input name="weight" lay-verify="required" placeholder="请输入商品重量"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">特价</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="is_discount" value="1" title="是">
                        <input type="radio" name="is_discount" value="0" title="否"  checked="">
                    </div>

                    <label class="layui-form-label">热卖</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="is_hot" value="1" title="是">
                        <input type="radio" name="is_hot" value="0" title="否"  checked="">
                    </div>

                    <label class="layui-form-label">高档</label>
                    <div class="layui-input-inline">
                        <input type="radio" name="is_upscale" value="1" title="是">
                        <input type="radio" name="is_upscale" value="0" title="否"  checked="">
                    </div>

                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品规格</label>
                    <div class="layui-input-block">
                        <table class="layui-table" lay-data="{id:'table_spec'}" lay-filter="table_spec">
                            <thead>
                            <tr>
                                <th lay-data="{field:'title', width:300, edit: 'text'}">规格名称</th>
                                <th lay-data="{field:'price', width:120, edit: 'text'}">单价</th>
                                <th lay-data="{field:'raw_price', width:120, edit: 'text'}">原价(特价展示)</th>
                                <th lay-data="{field:'stock', width:120, edit: 'text'}">库存</th>
                            </tr>
                            </thead>
                        </table>
                        <button class="layui-btn" type="button" id="addspec">添加</button>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">商品详情</label><div class="layui-input-block">
                    <textarea id="note" style="display: none; background: #fff;">{$info.note}</textarea>
                </div>
                </div>

                <input type="hidden" name="id">

                <!-- 隐藏输入框 用来存放上传后图片路径 -->
                <input id="credential_hide" name="image" type="hidden" lay-verify="credentialOne" autocomplete="off"
                       class="layui-input">

                <div class="layui-form-item">
                    <div class="layui-input-inline">
                        <button type="button" class="layui-btn" lay-submit="" lay-filter="submit"
                                id="submit">立即提交</button>
                        <a data-href="{:url('index')}" class="layui-btn layui-btn-primary back">返回</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

{include file="common/footer"/}
<script>
    layui.use(['form', 'layer', 'upload', 'table', 'layedit'], function () {
        var form = layui.form,
            layer = layui.layer,
            upload = layui.upload,
            table = layui.table,
            $ = layui.jquery;
        var layedit = layui.layedit;

        // 渲染编辑器
        layedit.set({
            uploadImage: {
                url: '{:url("api/upload/image")}' //接口url
                ,type: 'post' //默认post
            }
        });
        var note = layedit.build('note');

        var info = {:json_encode($info)};

        var spec = {:json_encode($spec)};
        var url = "{:url('add')}";
        if (info) {
            form.val('form', info);
            $('#demo1').attr('src', info.image);
            var url = "{:url('edit')}";



            // 规格
            table.reload("table_spec", {data: spec});

            // 多图
            var imgArr = info.images.split(';');
            if (imgArr.length>0) {
                for (var i=0; imgArr.length>i; i++) {
                    $('.uploader-list').append(
                        '<div id="" class="file-iteme">' +
                        '<div class="handle"><i class="layui-icon layui-icon-delete"></i></div>' +
                        '<img style="width: 180px;height: 120px;" src="'+imgArr[i]+'" alt="">' +
                        '</div>'
                    );
                }
            }

        }

        //返回页面
        $('body').on('click', '.back', function () {
            var url = $(this).attr('data-href');
            layer.closeAll();
            window.parent.location.href = url;
        });

        // 提交
        form.on('submit(submit)', function (d) {
            var data = d.field;

            if (data.image == ''){
                return layer.msg('请上传封面图片', {icon: 2, time:1200});
            }

            // 多图图片
            var imgArr = [];
            var upload_list = $('.file-iteme');
            if (upload_list.length<=0) {
                return layer.msg('请上传轮播图片', {icon: 2, time:1200});
            }
            for (var i = 0; upload_list.length>i; i++) {
                imgArr.push($(upload_list[i]).children('img').attr('src'));
            }
            data.images = imgArr.join(';'); // 所有图片

            // 规格
            data.spec = table.cache.table_spec
            if (data.spec == false){
                return layer.msg('请添加规格', {icon: 2, time:1200});
            }

            // 详情
            data.note = layedit.getContent(note)

            $.post(url, data, function (res) {
                if (res.code == 0) {
                    layer.msg(res.msg, { time: 1000, icon: 1 }, function () {
                        var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                        parent.layer.close(index); //再执行关闭
                        parent.location.reload();//刷新父页面，注意一定要在关闭当前iframe层之前执行刷新
                    });
                } else {
                    layer.msg(res.msg, { time: 1000, icon: 2 });
                }
            });
        })

        // 上传多图
        upload.render({
            elem: '#test2'
            ,url: '{:url("sys.uploads/uploads")}'
            ,data: { type: 'image', path: 'goods' }
            ,done: function(res){
                if(res.code>0){ //上传成功
                    $('.uploader-list').append(
                        '<div id="" class="file-iteme">' +
                        '<div class="handle"><i class="layui-icon layui-icon-delete"></i></div>' +
                        '<img style="width: 180px;height: 120px;" src="'+res.url+'" alt="">' +
                        '</div>'
                    );
                }
            }
        });

        // 鼠标悬停显示删除
        $(document).on("mouseenter mouseleave", ".file-iteme", function(event){
            if(event.type === "mouseenter"){
                //鼠标悬浮
                $(this).children(".info").fadeIn("fast");
                $(this).children(".handle").fadeIn("fast");
            }else if(event.type === "mouseleave") {
                //鼠标离开
                $(this).children(".info").hide();
                $(this).children(".handle").hide();
            }
        });

        // 删除图片
        $(document).on("click", ".file-iteme .handle", function(event){
            $(this).parent().remove();
        });

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '{:url("sys.uploads/uploads")}' //改成您自己的上传接口
            // , auto: false
            , data: { type: 'image', path: 'goods' }
            , size: 200
            // , bindAction: '#submit'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code = 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
                $('#credential_hide').val(res.url);
                return layer.msg('上传成功', { icon: 1, time: 1000 });
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        // 添加规格按钮_被点击
        $('#addspec').click(function(){
            var dataBak = []; // 新数组
            var tableBak = table.cache.table_spec; // 表格数据
            for (var i = 0; i < tableBak.length; i++) {
                dataBak.push(tableBak[i]);      // 将之前的数组备份
            }
            // 添加一条
            dataBak.push({
                id:null,
                title:'规格',
                price:0.00,
                stock:100,
            });
            // 重载数据
            table.reload("table_spec", {data:dataBak});
        });

        // 规格编辑
        table.on('edit(table_spec)', function(obj){
            var value = obj.value;
            var field = obj.field;
            var inputElem = $(this);
            var tdElem = inputElem.closest('td');
            var valueOld = inputElem.prev().text();
            var data = {};
            var errMsg = ''; // 错误信息
            if (field === 'stock') {
                if (!/^(0|\+?[1-9][0-9]*)$/.test(value)) {
                    errMsg = '请输入正确的值';
                }
            } else if (field === 'price') {
                if (!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(value)) {
                    errMsg = '请输入正确的金额, 保留两位小数';
                }
            }

            if (errMsg) {
                // 如果不满足的时候
                data[field] = valueOld;
                layer.msg(errMsg, {time: 1000, anim: 6, shade: 0.01}, function () {
                    inputElem.blur();
                    obj.update(data);
                    tdElem.click();
                });
            }
        });

        // 加载店铺列表
        $('#shop').html('');
        $.get("{:url('shops')}", function(e) {
            if (e.code==0) {
                for (var i=0; e.data.length>i; i++) {
                    $('#shop').append('<option value="'+e.data[i].id+'">'+e.data[i].name+'</option>');
                }
                form.render('select');
            }
        });

        // 首次分类
        $('#category').html('');
        $.get("{:url('category/getlist')}", {pid:0}, function(res) {
            if (res.code==0) {
                // 加载一级分类
                for (var i=0; res.data.length>i; i++) {
                    $('#category').append(
                        '<option value="'+res.data[i].id+'">'+res.data[i].title+'</option>');
                }
                $("#category").find("option[value="+info.category+"]").prop("selected",true);
                form.render('select');

                $('#category_two').html('');
                // 二级分类加载
                $.get("{:url('category/getlist')}", {pid: info.category}, function(e) {
                    if (e.code==0) {
                        for (var i=0; e.data.length>i; i++) {
                            $('#category_two').append('<option value="'+e.data[i].id+'">'+e.data[i].title+'</option>');
                        }
                        $("#category_two").find("option[value="+info.category_two+"]").prop("selected",true);
                        form.render('select');
                    }
                });
            }
        });

        // 监听一级分类被选择
        form.on('select(category)', function(data){
            $('#category_two').html('');
            $.get("{:url('category/getlist')}", {pid:data.value}, function(e) {
                if (e.code==0) {
                    for (var i=0; e.data.length>i; i++) {
                        $('#category_two').append('<option value="'+e.data[i].id+'">'+e.data[i].title+'</option>');
                    }
                    form.render('select');
                }
            });
        });

    });
</script>
<style type="text/css">
    .uploader-list .info {
        position: relative;
        margin-top: -25px;
        background-color: black;
        color: white;
        filter: alpha(Opacity=80);
        -moz-opacity: 0.5;
        opacity: 0.5;
        width: 180px;
        height: 25px;
        text-align: center;
        display: none;
    }

    .uploader-list .handle {
        position: relative;
        background-color: black;
        color: white;
        filter: alpha(Opacity=80);
        -moz-opacity: 0.5;
        opacity: 0.5;
        width: 180px;
        text-align: right;
        height: 18px;
        margin-bottom: -18px;
        display: none;
    }

    .uploader-list .handle i {
        margin-right: 5px;
    }

    .uploader-list .handle i:hover {
        cursor: pointer;
    }

    .uploader-list .file-iteme {
        margin: 12px 0 0 15px;
        padding: 1px;
        float: left;
    }
</style>